GrabImage.py

Get Image(s) via Polling

It shows how to get images via polling function. The major steps include creating a handle, turning on the camera, registering a callback, starting grabbing images, creating an image grabbing thread (image acquisition buffer is allocated by the user, and image acquisition is achieved by calling MV_CC_GetOneFrameTimeout()), stopping grabbing images, turning off the camera, and destroying the handle.

1 # -- coding: utf-8 --
2 
3 import sys
4 import platform
5 import threading
6 import os
7 from ctypes import *
8 
9 
10 # Compatible with different operating systems to load DDL
11 currentsystem = platform.system()
12 if currentsystem == 'Windows':
13  sys.path.append(os.path.join(os.getenv('MVCAM_COMMON_RUNENV'), "Samples", "Python", "MvImport"))
14 else:
15  sys.path.append(os.path.join("..", "..", "MvImport"))
16 
17 from MvCameraControl_class import *
18 
19 # Compatible with input processing of Python 2.X and 3.X
20 if sys.version_info[0] < 3: # Python 2
21  # Python 2.x
22  input_func = raw_input
23 else: # Python 3
24  # Python 3.x
25  input_func = input
26 
27 
28 # Decoding Characters
29 def decoding_char(ctypes_char_array):
30  """
31  Safely decode a string from a ctypes character array.
32  Compatible with Python 2.x and 3.x, as well as 32-bit and 64-bit environments.
33  """
34  byte_str = memoryview(ctypes_char_array).tobytes()
35 
36  # Truncate at the first null character
37  null_index = byte_str.find(b'\x00')
38  if null_index != -1:
39  byte_str = byte_str[:null_index]
40 
41  # Attempt to decode using multiple encodings
42  for encoding in ['gbk', 'utf-8', 'latin-1']:
43  try:
44  return byte_str.decode(encoding)
45  except UnicodeDecodeError:
46  continue
47 
48  # If all encodings fail, use a replacement strategy
49  return byte_str.decode('latin-1', errors='replace')
50 
51 
52 g_bExit = False
53 
54 # Customize the thread function
55 def work_thread(cam=0, pData=0, nDataSize=0):
56  stOutFrame = MV_FRAME_OUT()
57  memset(byref(stOutFrame), 0, sizeof(stOutFrame))
58  while True:
59  ret = cam.MV_CC_GetImageBuffer(stOutFrame, 1000)
60  if None != stOutFrame.pBufAddr and 0 == ret:
61  print ("get one frame: Width[%d], Height[%d], nFrameNum[%d]" % (stOutFrame.stFrameInfo.nWidth, stOutFrame.stFrameInfo.nHeight, stOutFrame.stFrameInfo.nFrameNum))
62  nRet = cam.MV_CC_FreeImageBuffer(stOutFrame)
63  else:
64  print ("no data[0x%x]" % ret)
65  if g_bExit == True:
66  break
67 
68 if __name__ == "__main__":
69 
70  try:
71  # Initialize SDK resources
72  MvCamera.MV_CC_Initialize()
73 
74  SDKVersion = MvCamera.MV_CC_GetSDKVersion()
75  print ("SDKVersion[0x%x]" % SDKVersion)
76  deviceList = MV_CC_DEVICE_INFO_LIST()
77  tlayerType = (MV_GIGE_DEVICE | MV_USB_DEVICE | MV_GENTL_CAMERALINK_DEVICE
78  | MV_GENTL_CXP_DEVICE | MV_GENTL_XOF_DEVICE)
79 
80  # Enumerate devices
81  ret = MvCamera.MV_CC_EnumDevices(tlayerType, deviceList)
82  if ret != 0:
83  print ("enum devices fail! ret[0x%x]" % ret)
84  sys.exit()
85 
86  if deviceList.nDeviceNum == 0:
87  print ("find no device!")
88  sys.exit()
89 
90  print ("Find %d devices!" % deviceList.nDeviceNum)
91 
92  for i in range(0, deviceList.nDeviceNum):
93  mvcc_dev_info = cast(deviceList.pDeviceInfo[i], POINTER(MV_CC_DEVICE_INFO)).contents
94  if mvcc_dev_info.nTLayerType == MV_GIGE_DEVICE or mvcc_dev_info.nTLayerType == MV_GENTL_GIGE_DEVICE:
95  print ("\ngige device: [%d]" % i)
96  strModeName = decoding_char(mvcc_dev_info.SpecialInfo.stGigEInfo.chModelName)
97  print ("device model name: %s" % strModeName)
98  strSerialNumber = decoding_char(mvcc_dev_info.SpecialInfo.stGigEInfo.chSerialNumber)
99  print("device serial number: %s" % strSerialNumber)
100  nip1 = ((mvcc_dev_info.SpecialInfo.stGigEInfo.nCurrentIp & 0xff000000) >> 24)
101  nip2 = ((mvcc_dev_info.SpecialInfo.stGigEInfo.nCurrentIp & 0x00ff0000) >> 16)
102  nip3 = ((mvcc_dev_info.SpecialInfo.stGigEInfo.nCurrentIp & 0x0000ff00) >> 8)
103  nip4 = (mvcc_dev_info.SpecialInfo.stGigEInfo.nCurrentIp & 0x000000ff)
104  print ("current ip: %d.%d.%d.%d\n" % (nip1, nip2, nip3, nip4))
105  elif mvcc_dev_info.nTLayerType == MV_USB_DEVICE:
106  print ("\nu3v device: [%d]" % i)
107  strModeName = decoding_char(mvcc_dev_info.SpecialInfo.stUsb3VInfo.chModelName)
108  print ("device model name: %s" % strModeName)
109 
110  strSerialNumber = decoding_char(mvcc_dev_info.SpecialInfo.stUsb3VInfo.chSerialNumber)
111  print ("device serial number: %s" % strSerialNumber)
112  elif mvcc_dev_info.nTLayerType == MV_GENTL_CAMERALINK_DEVICE:
113  print ("\nCML device: [%d]" % i)
114  strModeName = decoding_char(mvcc_dev_info.SpecialInfo.stCMLInfo.chModelName)
115  print ("device model name: %s" % strModeName)
116 
117  strSerialNumber = decoding_char(mvcc_dev_info.SpecialInfo.stCMLInfo.chSerialNumber)
118  print ("device serial number: %s" % strSerialNumber)
119  elif mvcc_dev_info.nTLayerType == MV_GENTL_CXP_DEVICE:
120  print ("\nCXP device: [%d]" % i)
121  strModeName = decoding_char(mvcc_dev_info.SpecialInfo.stCXPInfo.chModelName)
122  print ("device model name: %s" % strModeName)
123 
124  strSerialNumber = decoding_char(mvcc_dev_info.SpecialInfo.stCXPInfo.chSerialNumber)
125  print ("device serial number: %s" % strSerialNumber)
126  elif mvcc_dev_info.nTLayerType == MV_GENTL_XOF_DEVICE:
127  print ("\nXoF device: [%d]" % i)
128  strModeName = decoding_char(mvcc_dev_info.SpecialInfo.stXoFInfo.chModelName)
129  print ("device model name: %s" % strModeName)
130 
131  strSerialNumber = decoding_char(mvcc_dev_info.SpecialInfo.stXoFInfo.chSerialNumber)
132  print ("device serial number: %s" % strSerialNumber)
133 
134  nConnectionNum = input_func("please input the number of the device to connect:")
135 
136  if int(nConnectionNum) >= deviceList.nDeviceNum:
137  print ("intput error!")
138  sys.exit()
139 
140  # Create the camera instance
141  cam = MvCamera()
142 
143  # Select a device, and create a handle
144  stDeviceList = cast(deviceList.pDeviceInfo[int(nConnectionNum)], POINTER(MV_CC_DEVICE_INFO)).contents
145 
146  ret = cam.MV_CC_CreateHandle(stDeviceList)
147  if ret != 0:
148  raise Exception ("create handle fail! ret[0x%x]" % ret)
149 
150  # Turn on the device
151  ret = cam.MV_CC_OpenDevice(MV_ACCESS_Exclusive, 0)
152  if ret != 0:
153  raise Exception ("open device fail! ret[0x%x]" % ret)
154 
155  # Get optimal packet size (only supported by GigE devices)
156  if stDeviceList.nTLayerType == MV_GIGE_DEVICE or stDeviceList.nTLayerType == MV_GENTL_GIGE_DEVICE:
157  nPacketSize = cam.MV_CC_GetOptimalPacketSize()
158  if int(nPacketSize) > 0:
159  ret = cam.MV_CC_SetIntValue("GevSCPSPacketSize",nPacketSize)
160  if ret != 0:
161  print ("Warning: Set Packet Size fail! ret[0x%x]" % ret)
162  else:
163  print ("Warning: Get Packet Size fail! ret[0x%x]" % nPacketSize)
164 
165  # Set trigger mode to off
166  ret = cam.MV_CC_SetEnumValue("TriggerMode", MV_TRIGGER_MODE_OFF)
167  if ret != 0:
168  raise Exception ("set trigger mode fail! ret[0x%x]" % ret)
169 
170  # Start grabbing images
171  ret = cam.MV_CC_StartGrabbing()
172  if ret != 0:
173  raise Exception ("start grabbing fail! ret[0x%x]" % ret)
174 
175  try:
176  hThreadHandle = threading.Thread(target=work_thread, args=(cam, None, None))
177  hThreadHandle.start()
178  except:
179  print ("error: unable to start thread")
180 
181  print ("press Enter key to stop grabbing.")
182  input_func()
183 
184  g_bExit = True
185  hThreadHandle.join()
186 
187  # Stop grabbing images
188  ret = cam.MV_CC_StopGrabbing()
189  if ret != 0:
190  raise Exception ("stop grabbing fail! ret[0x%x]" % ret)
191 
192  # Turn off the device
193  ret = cam.MV_CC_CloseDevice()
194  if ret != 0:
195  raise Exception ("close deivce fail! ret[0x%x]" % ret)
196 
197  # Destroy the handle
198  cam.MV_CC_DestroyHandle()
199 
200  except Exception as e:
201  print(e)
202  cam.MV_CC_CloseDevice()
203  cam.MV_CC_DestroyHandle()
204  finally:
205  # Release SDK resources
206  MvCamera.MV_CC_Finalize()